<?php
/**
 * 用户统计
 * User: joker
 * Date: 2022/7/23
 * Time: 10:43
 */

namespace app\crontab\controller;

use app\admin\models\InvalidRemindModel;
use app\admin\models\UserModel;
use app\card\models\UserCardModel;
use app\card\service\CardProService;
use app\crontab\service\UserShellService;

class UserCensus{
//    protected $noNeedAction = ['*']; // 不需要校验控制器，通道
//    // 操作前置
//    protected $beforeActionList = ['my_initialize'];

    // 操作前置方法
    public function my_initialize()
    {
//        $this->is_admin();  // 权限检查
    }

    //定时统计当天数据
    public function census_user(){
        $data = input();
        // 是否开启重写
        if( isset($data['rewrite']) && !empty($data['rewrite']) && $data['rewrite'] == 'call' ){
            $UserModel =  new UserModel();
            // 起始时间
            $min_id=$UserModel->min("id");
            $min_id = obj_to_arr($min_id);
            if(!$min_id) exit();
            $createTime = $UserModel->where("id",$min_id)->value("createTime");
            // 开始时间
            $day_start = strtotime(date('Y-m-d',strtotime($createTime)));
            // 结束 时间
            $day_end = strtotime(date('Y-m-d'));
            for($i=$day_start;$i<$day_end;$i=$i +86400) {
                $temp_day=date('Y-m-d',$i);
                $this->census($temp_day);
            }
        }else{
            $this->census();
        }
        // 推送卡片失效提醒消息
        $this->send_user_card_msg();
        exit();
    }
    private  function census($new_time = null){
        $UserShellService = new UserShellService();
        $census =[];
        // 统计日期
        $census['census_time']= $new_time ? $new_time : date('Y-m-d', strtotime('-1 day', time()));  // 默认前一天
        // 总计人数
        $census['total_number'] = $UserShellService->s_user_total([
            'createTime' =>['<=',$census['census_time']." 23:59:59"]
        ]);

        // 认证总人数
        $census['attestation_number'] =$UserShellService->s_attestation_user([
            'create_time' =>['<=',$census['census_time']." 23:59:59"]
        ]);

        // 今日新增人数
        $census['add_number'] = $UserShellService->s_user_total([
            'createTime' =>['like',$census['census_time'].'%']
        ]);
        // 今日认证人数
        $census['add_attestation_number'] = $UserShellService->s_attestation_user([
            'create_time' =>['like',$census['census_time'].'%']
        ]);
        // 存储到数据库
        $UserShellService->s_save_census($census);
    }

    // 短信推送，告知用户续费
    public function send_user_card_msg(){
        // 获取月
        $this->send_user_card_months_msg();
        // 获取周
        $this->send_user_card_week_msg();
    }

    // 获取月
    public function send_user_card_months_msg(){
        // 提醒周期（1：周、2：月）
        $total_card = $this->get_send_card_user_list(2);
        if(count($total_card) == 0)  exit();
        foreach($total_card as $key=>$value){

            // 获取日期
            $time = date('Y-m-d H:i:s', $value['valid_time']);
            echo($time);
            $send_data = [
                'card_code' => $value['code'],
                'time' => $time,
            ];
            if(!empty($value['mobile']) && !empty($send_data['card_code']) && !empty($send_data['time'])){
                $res = $this->send_msg($value['mobile'],$send_data);
                if($res['Message'] == 'OK'){
                    // 存储添加记录
                    $this->add_invalid_remind($value,2);
                }
            }
        }
    }

    // 获取周
    public function send_user_card_week_msg(){
        // 提醒周期（1：周、2：月）
        $total_card = $this->get_send_card_user_list(1);
        if(count($total_card) == 0)  exit();
        foreach($total_card as $key=>$value){
            // 获取日期
            $time = date('Y-m-d H:i:s', $value['valid_time']);
            $send_data = [
                'card_code' => $value['code'],
                'time' => $time,
            ];
            if(!empty($value['mobile']) && !empty($send_data['card_code']) && !empty($send_data['time'])){
                $res = $this->send_msg($value['mobile'],$send_data);
                if($res['Message'] == 'OK'){
                    // 存储添加记录
                    $this->add_invalid_remind($value,1);
                }
            }
        }
    }

    // 添加发送记录
    public function add_invalid_remind($data,$r_type){
        $InvalidRemindModel =  new InvalidRemindModel();
        $res = $InvalidRemindModel->where('cu_id',$data['cu_id'])->where('r_type',$r_type)->where('pid',$data['pid'])->find();
        if($res) return false;
        // 添加
        $InvalidRemindModel->insert([
            'cu_id'     => $data['cu_id'],
            'r_type'    => $r_type,
            'pid'       => $data['pid'],
        ]);
    }

    // 发送短信失效提前通知
    public function send_msg($phone,$send_data){
        if(empty($phone)) json_err(-210,['电话号码，不能为空！']);
        // 初始化SendSmsRequest实例用于设置发送短信的参数
        import('aliyun-dysms-php-sdk.api_demo.SmsDemo',VENDOR_PATH,'.php');
        $SmsDemo = new \SmsDemo();
        $res = $SmsDemo->sendSms($phone,config('signName'),config('invalidTemplateCode'),$send_data);
        if($res->Code == 'OK'){
            return obj_to_arr($res);
        }else{
            json_err(-210,[$res->Message]);
            exit();
        }
    }


    // 获取推送数据
    public function get_send_card_user_list($type){
        // 获取绑定卡片数据
        $UserCardModel =  new UserCardModel();

        if($type == 2){
            // 获取提前一个月
            $valid_date = date('Y-m-d H:i:s', strtotime('+1 months'));
        }else{
            // 提前一周
            $valid_date = date('Y-m-d H:i:s', strtotime('+7 day'));
        }
        $time = strtotime($valid_date);

        // 获取提醒表中是否已经提醒过了
        $InvalidRemindModel = new InvalidRemindModel();
        $send_card_invali  =$InvalidRemindModel->where('r_type',$type)->field('pid')->select();
        $invali_ids = array_column($send_card_invali, 'pid');
        // 获取提醒表中是否已经提醒过了
        $total_card = $UserCardModel->alias('a')
            ->where('a.valid_time','<',$time)
            ->where('a.pid','not in',$invali_ids)
            ->join('identity_card b','b.uid = a.uid')
            ->join('card_product c','c.pid = a.pid')
            ->select();
        return obj_to_arr($total_card);
    }


}
